# encoding=utf-8
import logging
from pyquery import PyQuery
from henan.utils.session_helper import SessionHelper
from zc_core.middlewares.proxies.proxy_facade import ProxyFacade
from zc_core.util.http_util import retry_request
from henan.utils.order_captcha import OrderCaptchaHelper

logger = logging.getLogger(__name__)


class SessionMiddleware(object):
    def __init__(self):
        self.session_helper = SessionHelper()

    def process_request(self, request, spider):
        meta = request.meta
        req_type = meta.get('reqType', None)
        if req_type and req_type in ['sku', 'item']:
            session_id = self.session_helper.get_session()
            if session_id:
                request.headers['Cookie'] = 'SESSION={}'.format(session_id)
                request.meta['session'] = session_id
            else:
                spider.logger.error('无可用SESSION=%s' % session_id)
                return retry_request(request)

    def process_response(self, request, response, spider):
        meta = request.meta

        req_type = meta.get('reqType', None)
        if req_type and req_type in ['sku', 'item']:
            session_id = meta.get('session', '')
            if '长时间未操作，请重试!' in response.text:
                self.session_helper.remove(session_id)
                logger.info('会话失效重试: session=%s' % session_id)
                return retry_request(request)
            elif '找不到对应的页面' in response.text:
                logger.info('网站异常: requests=%s' % request.url)
        return response


class OrderCaptchaMiddleware(object):
    """
    订单验证码挂载中间件
    备注：如果挂载代理，代理需要在本中间件之前挂载
    """
    captcha_helper = OrderCaptchaHelper()
    proxy_facade = ProxyFacade()

    def process_request(self, request, spider):
        meta = request.meta
        proxy = self.proxy_facade.get_proxy()
        req_type = meta.get('reqType', None)
        if req_type and 'order' == req_type:
            code = self.captcha_helper.get_captcha_code(proxy)
            if code:
                request._set_url(request.url.split('?')[0] + f'?code={code}')
                request.meta['code'] = code
                request.meta['proxy'] = "http://" + proxy
            else:
                spider.logger.error('无可用验证码重试: proxy=%s, page=%s' % (proxy, meta.get('page')))
                return retry_request(request)

    def process_response(self, request, response, spider):
        meta = request.meta
        req_type = meta.get('reqType', None)
        if req_type and 'order' == req_type:
            proxy = meta.get('proxy', 'NO_PROXY')
            code = meta.get('code', '')
            # 异常列表
            if '>详情</a>' not in response.text:
                # 重置验证码
                self.captcha_helper.reset(proxy)
                logger.info('验证码失效重试: proxy=%s, code=%s, page=%s' % (proxy, code, meta.get('page')))

                return retry_request(request)

        return response

    def process_exception(self, request, exception, spider):
        meta = request.meta
        proxy = meta.get('proxy', 'NO_PROXY')
        req_type = meta.get('reqType', None)
        if req_type and 'order' == req_type:
            logger.info('订单请求异常重试: proxy=%s, code=%s, page=%s' % (proxy, meta.get('code'), meta.get('page')))
            return retry_request(request)
